package com.jeeplus.itemInterface.subInterface;

import com.jeeplus.common.json.AjaxJson;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.freezingassets.entity.FreezingAssets;
import com.jeeplus.modules.freezingassets.service.FreezingAssetsService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;

import com.jeeplus.modules.positionassets.entity.PositionAssets;
import com.jeeplus.modules.positionassets.entity.PositionRecord;
import com.jeeplus.modules.positionassets.service.PositionAssetsService;
import com.jeeplus.modules.positionorder.entity.PositionOrder;
import com.jeeplus.modules.positionorder.service.PositionOrderService;
import com.jeeplus.modules.purchaseorder.entity.PurchaseOrder;
import com.jeeplus.modules.purchaseorder.entity.TradeOrder;
import com.jeeplus.modules.purchaseorder.service.PurchaseOrderService;
import com.jeeplus.modules.saleorder.entity.SaleOrder;
import com.jeeplus.modules.saleorder.service.SaleOrderService;

import com.jeeplus.modules.subgoods.entity.GoodsQuotation;
import com.jeeplus.modules.subgoods.entity.SubGoods;
import com.jeeplus.modules.subgoods.service.SubGoodsService;
import com.jeeplus.modules.subrecord.entity.SubRecord;
import com.jeeplus.modules.subrecord.service.SubRecordService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.takegoods.entity.TakeGoods;
import com.jeeplus.modules.takegoods.service.TakeGoodsService;
import com.jeeplus.modules.takeorder.entity.TakeOrder;
import com.jeeplus.modules.takeorder.service.TakeOrderService;
import com.jeeplus.modules.traderecord.entity.TradeLineInfo;
import com.jeeplus.modules.traderecord.entity.TradeRecord;
import com.jeeplus.modules.traderecord.service.TradeRecordService;
import com.jeeplus.modules.tradingline.entity.TradingLine;
import com.jeeplus.modules.tradingline.service.TradingLineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Api(value = "subInterfaceController",description = "认购相关接口")
@Controller
@RequestMapping(value = "${frontPath}/sub")
public class subInterfaceController {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MemberService memberService;
    @Autowired
    private SubGoodsService subGoodsService;
    @Autowired
    private SubRecordService subRecordService;
    @Autowired
    private TakeGoodsService takeGoodsService;
    @Autowired
    private TakeOrderService takeOrderService;
    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private SaleOrderService saleOrderService;
    @Autowired
    private TradeRecordService tradeRecordService;
    @Autowired
    private PositionAssetsService positionAssetsService;
    @Autowired
    private FreezingAssetsService freezingAssetsService;
    @Autowired
    private PositionOrderService positionOrderService;


    @ApiOperation(value = "获取认购商品",notes = "获取认购商品")
    @GetMapping("/getSubGoods")
    @ResponseBody
    public AjaxJson getSubGoods(){
        AjaxJson aj = new AjaxJson();
        List<SubGoods> goodsList = subGoodsService.findGoods(new SubGoods());
        aj.put("goodsList",goodsList);
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "认购商品详情",notes = "认购商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getSubGoodsDetail")
    @ResponseBody
    public AjaxJson getSubGoodsDetail(String goodsId){
        AjaxJson aj = new AjaxJson();
        SubGoods subGoods = subGoodsService.get(goodsId);
        if (subGoods != null){
            subGoods.setNum(subGoods.getOrigianNum());
            aj.put("subGoods",subGoods);
            aj.setSuccess(true);
        }else {
            aj.setSuccess(false);
            aj.setMsg("商品信息有误");
        }
        return aj;
    }


    @ApiOperation(value = "获取提货商品",notes = "获取提货商品")
    @GetMapping("/gettakeGoods")
    @ResponseBody
    public AjaxJson gettakeGoods(){
        AjaxJson aj = new AjaxJson();
        List<TakeGoods> goodsList = takeGoodsService.findAllList(new TakeGoods());
        if (goodsList.size() > 0){
            for (TakeGoods takeGoods : goodsList) {
                takeGoods.setDeliveryMethod(DictUtils.getDictLabel(takeGoods.getDeliveryMethod(),"take_delivery",""));
            }
        }
        aj.put("goodsList",goodsList);
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "提货商品详情",notes = "提货商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getTakeGoodsDetail")
    @ResponseBody
    public AjaxJson getTakeGoodsDetail(String goodsId){
        AjaxJson aj = new AjaxJson();
        TakeGoods takeGoods = takeGoodsService.get(goodsId);
        if (takeGoods != null){
            aj.put("takeGoods",takeGoods);
            aj.setSuccess(true);
        }else {
            aj.setSuccess(false);
            aj.setMsg("商品信息有误");
        }
        return aj;
    }


    @ApiOperation(value = "确认认购",notes = "确认认购")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "认购数量(5的倍数)",name = "num",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query")
    })
    @PostMapping("/confirmSubscription")
    @ResponseBody
    public AjaxJson confirmSubscription(String goodsId,String memberId,int num){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            Jedis jedis = new Jedis("localhost",6379);
            Long result = jedis.setnx(memberId,memberId);
            if (result == 1){
                //设置有效期10秒
                jedis.expire(memberId,10);
                aj = subRecordService.subscription(member,goodsId,num);
                jedis.del(memberId);
            }
//            else {
//                aj.setSuccess(false);
//                aj.setMsg("当前抢购人数过多，请重试！");
//                return aj;
//            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }


    @ApiOperation(value = "确认提货",notes = "确认提货")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "提货数量",name = "num",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "积分中心",name = "serviceId",required = true,dataType = "String",paramType = "query"),
    })
    @PostMapping("/confirmTakeGoods")
    @ResponseBody
    public AjaxJson confirmTakeGoods(String goodsId,String memberId,int num, String serviceId){

        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            aj = takeOrderService.takeYourGoods(goodsId,member,num,serviceId);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }


//    @ApiOperation(value = "完成提货",notes = "完成提货")
//    @ApiImplicitParams({
//            @ApiImplicitParam(value = "订单编号",name = "orderNo",required = true,dataType = "String",paramType = "query"),
//            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query")
//    })
//    @PostMapping("/completeTakeGoods")
//    @ResponseBody
//    public AjaxJson completeTakeGoods(String orderNo,String memberId){
//        AjaxJson aj = new AjaxJson();
//        Member member = memberService.get(memberId);
//        if (member != null){
//            aj = takeOrderService.completeTake(member,orderNo);
//        }else {
//            aj.setSuccess(false);
//            aj.setMsg("用户信息有误");
//        }
//        return aj;
//    }


    @ApiOperation(value = "买入",notes = "买入")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "价格",name = "price",required = true,dataType = "double",paramType = "query"),
            @ApiImplicitParam(value = "数量",name = "num",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "手续费（固定0）",name = "charge",required = true,dataType = "double",paramType = "query"),
            @ApiImplicitParam(value = "总价",name = "totalPrice",required = true,dataType = "double",paramType = "query"),
    })
    @PostMapping("/confirmPurchase")
    @ResponseBody
    public AjaxJson confirmPurchase(String goodsId,String memberId,double price,int num,double charge,double totalPrice){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            //加锁，限制用户排队买入
            Jedis jedis = new Jedis("localhost",6379);
//                Long result = jedis.setnx(memberId,memberId);
                Long result = jedis.setnx("is_trding","1");
                if (result == 1){
                    //设置有效期10秒
                    jedis.expire("is_trding",3);
                    aj = purchaseOrderService.purchaseGoods(goodsId,member,price,num,charge,totalPrice);
                    jedis.del("is_trding");
                }
//            else {
//                aj.setSuccess(false);
//                aj.setMsg("操作频繁，请稍候！");
//                return aj;
//            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }



    @ApiOperation(value = "卖出",notes = "卖出")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "价格",name = "price",required = true,dataType = "double",paramType = "query"),
            @ApiImplicitParam(value = "数量",name = "num",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "手续费（总价的10%）",name = "charge",required = true,dataType = "double",paramType = "query"),
            @ApiImplicitParam(value = "总价",name = "totalPrice",required = true,dataType = "double",paramType = "query"),
    })
    @PostMapping("/confirmSale")
    @ResponseBody
    public AjaxJson confirmSale(String goodsId,String memberId,double price,int num,double charge,double totalPrice){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            //加锁，限制用户排队买入
            Jedis jedis = new Jedis("localhost",6379);
//            Long result = jedis.setnx(memberId,memberId);
            Long result = jedis.setnx("is_trding","1");
            if (result == 1){
                //设置有效期10秒
//                jedis.expire(memberId,10);
                jedis.expire("is_trding",3);
                aj = saleOrderService.saleGoods(goodsId,member,price,num,charge,totalPrice);
//                jedis.del(memberId);
                jedis.del("is_trding");
            }
//            else {
//                aj.setSuccess(false);
//                aj.setMsg("当前买卖人数过多，请重试！");
//                return aj;
//            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }


    @ApiOperation(value = "获取待成交订单",notes = "获取待成交订单")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "状态（0待成交1已成交2已撤销）",name = "flag",required = true,dataType = "String",paramType = "query"),
    })
    @GetMapping("/getToBeConcludedList")
    @ResponseBody
    public AjaxJson getToBeConcludedList(String memberId,String flag){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            List<TradeOrder> tradeOrders = new ArrayList<>();
            switch (flag){
                case "0":
                    PurchaseOrder purchaseOrder = new PurchaseOrder();
                    purchaseOrder.setIsDeal("0");
                    purchaseOrder.setIsRevoke("0");
                    purchaseOrder.setMember(member);
                    List<PurchaseOrder> purchaseOrderList = purchaseOrderService.findLimitList(purchaseOrder);
                    if (purchaseOrderList.size()>0){
                        for (PurchaseOrder order : purchaseOrderList) {
                            TradeOrder tradeOrder = new TradeOrder();
                            tradeOrder.setMember(member);
                            tradeOrder.setNum(order.getNonNum());
                            tradeOrder.setOrderNo(order.getOrderNo());
                            tradeOrder.setPrice(order.getPrice());
                            tradeOrder.setSubGoods(order.getSubGoods());
                            tradeOrder.setType("0");
                            tradeOrder.setOrderDate(order.getCreateDate());
                            tradeOrders.add(tradeOrder);
                        }
                    }
                    SaleOrder saleOrder = new SaleOrder();
                    saleOrder.setIsDeal("0");
                    saleOrder.setIsRevoke("0");
                    saleOrder.setMember(member);
                    List<SaleOrder> saleOrderList = saleOrderService.findLimitList(saleOrder);
                    if (saleOrderList.size()>0){
                        for (SaleOrder order : saleOrderList) {
                            TradeOrder tradeOrder = new TradeOrder();
                            tradeOrder.setMember(member);
                            tradeOrder.setNum(order.getNonNum());
                            tradeOrder.setOrderNo(order.getOrderNo());
                            tradeOrder.setPrice(order.getPrice());
                            tradeOrder.setSubGoods(order.getSubGoods());
                            tradeOrder.setType("1");
                            tradeOrder.setOrderDate(order.getCreateDate());
                            tradeOrders.add(tradeOrder);
                        }
                    }
                    tradeOrders = tradeOrders.stream().sorted(Comparator.comparing(TradeOrder::getOrderDate).reversed()).collect(Collectors.toList());
                    aj.setSuccess(true);
                    aj.put("tradeOrders",tradeOrders);
                    return aj;
                case "1":
                    TradeRecord tradeRecord = new TradeRecord();
                    tradeRecord.setPurchaseMember(member);
                    List<TradeRecord> pTrades = tradeRecordService.findLimitList(tradeRecord);
                    if (pTrades.size()>0){
                        for (TradeRecord pTrade : pTrades) {
                            TradeOrder tradeOrder = new TradeOrder();
                            tradeOrder.setMember(member);
                            tradeOrder.setNum(pTrade.getNum());
                            tradeOrder.setPrice(pTrade.getPrice());
                            tradeOrder.setSubGoods(pTrade.getSubGoods());
                            tradeOrder.setType("0");
                            tradeOrder.setOrderDate(pTrade.getCreateDate());
                            tradeOrders.add(tradeOrder);
                        }
                    }
                    TradeRecord tradeRecord1 = new TradeRecord();
                    tradeRecord1.setSaleMember(member);
                    List<TradeRecord> sTrades = tradeRecordService.findLimitList(tradeRecord1);
                    if (pTrades.size()>0){
                        for (TradeRecord pTrade : sTrades) {
                            TradeOrder tradeOrder = new TradeOrder();
                            tradeOrder.setMember(member);
                            tradeOrder.setNum(pTrade.getNum());
                            tradeOrder.setPrice(pTrade.getPrice());
                            tradeOrder.setSubGoods(pTrade.getSubGoods());
                            tradeOrder.setType("1");
                            tradeOrder.setOrderDate(pTrade.getCreateDate());
                            tradeOrders.add(tradeOrder);
                        }
                    }
                    tradeOrders = tradeOrders.stream().sorted(Comparator.comparing(TradeOrder::getOrderDate).reversed()).collect(Collectors.toList());
                    aj.setSuccess(true);
                    aj.put("tradeOrders",tradeOrders);
                    return aj;
                case "2":
                    PurchaseOrder purchaseOrder1 = new PurchaseOrder();
                    purchaseOrder1.setIsDeal("0");
                    purchaseOrder1.setIsRevoke("1");
                    purchaseOrder1.setMember(member);
                    List<PurchaseOrder> purchaseOrderList1 = purchaseOrderService.findLimitList(purchaseOrder1);
                    if (purchaseOrderList1.size()>0){
                        for (PurchaseOrder order : purchaseOrderList1) {
                            TradeOrder tradeOrder = new TradeOrder();
                            tradeOrder.setMember(member);
                            tradeOrder.setNum(order.getNonNum());
                            tradeOrder.setOrderNo(order.getOrderNo());
                            tradeOrder.setPrice(order.getPrice());
                            tradeOrder.setSubGoods(order.getSubGoods());
                            tradeOrder.setType("0");
                            tradeOrder.setOrderDate(order.getCreateDate());
                            tradeOrders.add(tradeOrder);
                        }
                    }
                    SaleOrder saleOrder1 = new SaleOrder();
                    saleOrder1.setIsDeal("0");
                    saleOrder1.setIsRevoke("1");
                    saleOrder1.setMember(member);
                    List<SaleOrder> saleOrderList1 = saleOrderService.findLimitList(saleOrder1);
                    if (saleOrderList1.size()>0){
                        for (SaleOrder order : saleOrderList1) {
                            TradeOrder tradeOrder = new TradeOrder();
                            tradeOrder.setMember(member);
                            tradeOrder.setNum(order.getNonNum());
                            tradeOrder.setOrderNo(order.getOrderNo());
                            tradeOrder.setPrice(order.getPrice());
                            tradeOrder.setSubGoods(order.getSubGoods());
                            tradeOrder.setType("1");
                            tradeOrder.setOrderDate(order.getCreateDate());
                            tradeOrders.add(tradeOrder);
                        }
                    }
                    tradeOrders = tradeOrders.stream().sorted(Comparator.comparing(TradeOrder::getOrderDate).reversed()).collect(Collectors.toList());
                    aj.setSuccess(true);
                    aj.put("tradeOrders",tradeOrders);
                    return aj;
                default:
                    aj.setSuccess(true);
                    aj.put("tradeOrders",tradeOrders);
                    return aj;
            }

        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }



    @ApiOperation(value = "获取指定商品待成交订单",notes = "获取指定商品待成交订单")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "类型（0买入1卖出）",name = "flag",required = true,dataType = "String",paramType = "query"),
    })
    @GetMapping("/getGoodsToBeConcludedList")
    @ResponseBody
    public AjaxJson getGoodsToBeConcludedList(String memberId,String goodsId,String flag){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            SubGoods subGoods = subGoodsService.get(goodsId);
            List<TradeOrder> tradeOrders = new ArrayList<>();
            List<TradeOrder> pOrders = new ArrayList<>();
            List<TradeOrder> sOrders = new ArrayList<>();
            if ("0".equals(flag)){
                PurchaseOrder purchaseOrder = new PurchaseOrder();
//                purchaseOrder.setIsDeal("0");
//                purchaseOrder.setIsRevoke("0");
                purchaseOrder.setSubGoods(subGoods);
//                purchaseOrder.setMember(member);
                List<PurchaseOrder> purchaseOrderList = purchaseOrderService.findLimitByPriceList(purchaseOrder);
                if (purchaseOrderList.size()>0){
                    for (PurchaseOrder order : purchaseOrderList) {
                        TradeOrder tradeOrder = new TradeOrder();
                        tradeOrder.setMember(member);
                        tradeOrder.setNum(order.getNonNum());
                        tradeOrder.setOrderNo(order.getOrderNo());
                        tradeOrder.setPrice(order.getPrice());
                        tradeOrder.setSubGoods(order.getSubGoods());
                        tradeOrder.setType("0");
                        tradeOrder.setOrderDate(order.getCreateDate());
                        pOrders.add(tradeOrder);
                    }
                    pOrders = pOrders.stream().sorted(Comparator.comparing(TradeOrder::getPrice).reversed()).collect(Collectors.toList());
                    tradeOrders.addAll(pOrders);
                }
            }else {
                SaleOrder saleOrder = new SaleOrder();
//                saleOrder.setIsDeal("0");
//                saleOrder.setIsRevoke("0");
                saleOrder.setSubGoods(subGoods);
//                saleOrder.setMember(member);
                List<SaleOrder> saleOrderList = saleOrderService.findLimitByPriceList(saleOrder);
                if (saleOrderList.size()>0){
                    for (SaleOrder order : saleOrderList) {
                        TradeOrder tradeOrder = new TradeOrder();
                        tradeOrder.setMember(member);
                        tradeOrder.setNum(order.getNonNum());
                        tradeOrder.setOrderNo(order.getOrderNo());
                        tradeOrder.setPrice(order.getPrice());
                        tradeOrder.setSubGoods(order.getSubGoods());
                        tradeOrder.setType("1");
                        tradeOrder.setOrderDate(order.getCreateDate());
                        sOrders.add(tradeOrder);
                    }
                    sOrders = sOrders.stream().sorted(Comparator.comparing(TradeOrder::getPrice)).collect(Collectors.toList());
                    tradeOrders.addAll(sOrders);
                }
            }

            aj.setSuccess(true);
            aj.put("tradeOrders",tradeOrders);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }


    @ApiOperation(value = "撤销",notes = "撤销")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单编号",name = "orderNo",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "类型（0买入1卖出）",name = "flag",required = true,dataType = "String",paramType = "query"),
    })
    @PostMapping("/revokeOrder")
    @ResponseBody
    public AjaxJson revokeOrder(String orderNo,String memberId,String flag){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            switch (flag){
                case "0":
                    aj = purchaseOrderService.revokePurchaseOrder(member,orderNo);
                    return aj;
                case "1":
                    aj = saleOrderService.revokeSaleOrder(member,orderNo);
                    return aj;
                default:
                    aj.setSuccess(true);
                    return aj;
            }

        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }


    @ApiOperation(value = "我的持仓",notes = "我的持仓")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getMyPosition")
    @ResponseBody
    public AjaxJson getMyPosition(String memberId){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        List<PositionRecord> positionRecordList = new ArrayList<>();
        if (member != null){
            PositionAssets positionAssets = new PositionAssets();
            positionAssets.setMember(member);
            positionAssets.setIsApply("0");
            List<PositionAssets> list = positionAssetsService.findList(positionAssets);
            if (list.size()>0){
                for (PositionAssets assets : list) {
                    PositionRecord positionRecord = new PositionRecord();
                    positionRecord.setName(assets.getGoodsName());
                    positionRecord.setNowPrice(assets.getNowPrice());
                    positionRecord.setNowTotal(assets.getNowTotal());
                    positionRecord.setNum(assets.getGoodsNum());
                    positionRecord.setPrice(assets.getGoodsPrice());
                    positionRecord.setUpPrice(assets.getNowPrice()-assets.getGoodsPrice());
                    positionRecord.setUpPercent(BigDecimal.valueOf(assets.getNowPrice()-assets.getGoodsPrice())
                            .divide(BigDecimal.valueOf(assets.getGoodsPrice()),2,BigDecimal.ROUND_HALF_DOWN)
                            .multiply(BigDecimal.valueOf(100)).doubleValue());
                    positionRecordList.add(positionRecord);
                }
                positionRecordList = positionRecordList.stream().sorted(Comparator.comparing(PositionRecord::getNowPrice).reversed()).collect(Collectors.toList());
            }
            aj.setSuccess(true);
            aj.put("positionRecordList",positionRecordList);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }


    @ApiOperation(value = "市场行情",notes = "市场行情")
    @ApiImplicitParams({
//            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getMarketQuotation")
    @ResponseBody
    public AjaxJson getMarketQuotation(){
        AjaxJson aj = new AjaxJson();
        List<GoodsQuotation> list = new ArrayList<>();
        //查询所有认购商品
        SubGoods subGoods1 = new SubGoods();
        subGoods1.setIsUnloading("0");
        List<SubGoods> goodsList = subGoodsService.findList(subGoods1);
        if (goodsList.size()>0){
            for (SubGoods subGoods : goodsList) {
                GoodsQuotation goodsQuotation = new GoodsQuotation();
                goodsQuotation.setGoodsId(subGoods.getId());
                goodsQuotation.setGoodsName(subGoods.getGoodsName());
                goodsQuotation.setHighest(subGoods.getPrice());
                goodsQuotation.setMinimum(subGoods.getPrice());
                goodsQuotation.setPrice(subGoods.getPrice());
                goodsQuotation.setTodayPrice(subGoods.getPrice());
                goodsQuotation.setTotalNum(0);
                goodsQuotation.setTotalPrice(0.0);
                goodsQuotation.setUpPercent(0.0);
                goodsQuotation.setUpPrice(0.0);
                goodsQuotation.setYesterdayPrice(0.0);
                goodsQuotation.setStock(subGoods.getStock());
                goodsQuotation.setSortDate(subGoods.getCreateDate());
                //查询认购商品相关的交易记录
                TradeRecord tradeRecord = new TradeRecord();
                tradeRecord.setSubGoods(subGoods);
                List<TradeRecord> tradeRecordList = tradeRecordService.findList(tradeRecord);
                if (tradeRecordList.size()>0){
//                    for (TradeRecord record : tradeRecordList) {
//                        record.setTotalPrice(record.getPrice()*record.getNum());
//                    }
                    //查询当日最高价 最低价  总成交量
                    List<TradeRecord> records = tradeRecordService.findGoodsInfoByDays();
                    if (records.size()>0){
                        for (TradeRecord record : records) {
                            if (subGoods.getId().equals(record.getSubGoods().getId())){
                                goodsQuotation.setHighest(record.getMaxPrice());
                                goodsQuotation.setMinimum(record.getMinPrice());
                                goodsQuotation.setTotalNum(record.getTotalNum());
                            }
                        }
                    }
                    //查询昨日价
                    List<TradeRecord> yesterdayInfo = tradeRecordService.findYesterdayInfo(subGoods.getId());
                    if (yesterdayInfo.size()>0){
                        goodsQuotation.setYesterdayPrice(yesterdayInfo.get(0).getPrice());
                    }
                    List<TradeRecord> yesterdayBeforeInfo = tradeRecordService.findYesterdayBeforeInfo(subGoods.getId());
                    //今日首次成交价
                    goodsQuotation.setTodayPrice(tradeRecordList.get(0).getPrice());
                    if (tradeRecordList.size()>1){
                        BigDecimal upPrice = BigDecimal.valueOf(tradeRecordList.get(0).getPrice()-(yesterdayBeforeInfo.size()>0?yesterdayBeforeInfo.get(0).getPrice():0));
                        BigDecimal upPercent = BigDecimal.valueOf(0);
                        if (yesterdayBeforeInfo.size() > 0) {
                            upPercent = upPrice.divide(BigDecimal.valueOf(yesterdayBeforeInfo.get(0).getPrice()),3,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                        }
                        goodsQuotation.setUpPrice(tradeRecordList.get(0).getPrice()-(yesterdayBeforeInfo.size()>0?yesterdayBeforeInfo.get(0).getPrice():0));
                        goodsQuotation.setUpPercent(upPercent.doubleValue());
                        goodsQuotation.setPrice(tradeRecordList.get(0).getPrice());
                    }
                    goodsQuotation.setTotalPrice(tradeRecordList.stream().mapToDouble(TradeRecord::getTotalPrice).sum());
                }else {
                    goodsQuotation.setHighest(subGoods.getPrice());
                    goodsQuotation.setMinimum(subGoods.getPrice());
                    goodsQuotation.setPrice(subGoods.getPrice());
                    goodsQuotation.setTodayPrice(subGoods.getPrice());
                    goodsQuotation.setTotalNum(0);
                    goodsQuotation.setTotalPrice(0.0);
                    goodsQuotation.setUpPercent(0.0);
                    goodsQuotation.setUpPrice(0.0);
                    goodsQuotation.setYesterdayPrice(0.0);
                }
                list.add(goodsQuotation);
            }
            list = list.stream().sorted(Comparator.comparing(GoodsQuotation::getUpPrice).reversed().thenComparing(GoodsQuotation::getSortDate)).collect(Collectors.toList());
        }
        aj.put("list",list);
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "商品市场行情",notes = "市场行情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getGoodsMarketQuotation")
    @ResponseBody
    public AjaxJson getGoodsMarketQuotation(String goodsId){
        AjaxJson aj = new AjaxJson();
        GoodsQuotation goodsQuotation = new GoodsQuotation();
        //认购商品
        SubGoods subGoods = subGoodsService.get(goodsId);
        if (subGoods != null){

                goodsQuotation.setGoodsId(subGoods.getId());
                goodsQuotation.setGoodsName(subGoods.getGoodsName());
                goodsQuotation.setHighest(subGoods.getPrice());
                goodsQuotation.setMinimum(subGoods.getPrice());
                goodsQuotation.setPrice(subGoods.getPrice());
                goodsQuotation.setTodayPrice(subGoods.getPrice());
                goodsQuotation.setTotalNum(0);
                goodsQuotation.setTotalPrice(0.0);
                goodsQuotation.setUpPercent(0.0);
                goodsQuotation.setUpPrice(0.0);
                goodsQuotation.setYesterdayPrice(0.0);
                //查询认购商品相关的交易记录
                TradeRecord tradeRecord = new TradeRecord();
                tradeRecord.setSubGoods(subGoods);
                List<TradeRecord> tradeRecordList = tradeRecordService.findList(tradeRecord);
                if (tradeRecordList.size()>0){
//                    for (TradeRecord record : tradeRecordList) {
//                        record.setTotalPrice(record.getPrice()*record.getNum());
//                    }
                    //查询当日最高价 最低价  总成交量
                    List<TradeRecord> records = tradeRecordService.findGoodsInfoByDays();
                    if (records.size()>0){
                        for (TradeRecord record : records) {
                            if (subGoods.getId().equals(record.getSubGoods().getId())){
                                goodsQuotation.setHighest(record.getMaxPrice());
                                goodsQuotation.setMinimum(record.getMinPrice());
                                goodsQuotation.setTotalNum(record.getTotalNum());
                            }
                        }
                    }
                    //查询昨日价
                    List<TradeRecord> yesterdayInfo = tradeRecordService.findYesterdayInfo(subGoods.getId());
                    if (yesterdayInfo.size()>0){
                        goodsQuotation.setYesterdayPrice(yesterdayInfo.get(0).getPrice());
                    }
                    List<TradeRecord> yesterdayBeforeInfo = tradeRecordService.findYesterdayBeforeInfo(subGoods.getId());
                    //今日首次成交价
                    goodsQuotation.setTodayPrice(tradeRecordList.get(0).getPrice());
                    if (tradeRecordList.size()>1){
                        BigDecimal upPrice = BigDecimal.valueOf(tradeRecordList.get(0).getPrice()-(yesterdayBeforeInfo.size()>0?yesterdayBeforeInfo.get(0).getPrice():0));
                        BigDecimal upPercent = BigDecimal.valueOf(0);
                        if (yesterdayBeforeInfo.size() > 0) {
                            upPercent = upPrice.divide(BigDecimal.valueOf(yesterdayBeforeInfo.get(0).getPrice()),3,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                        }
                        goodsQuotation.setUpPrice(tradeRecordList.get(0).getPrice()-(yesterdayBeforeInfo.size()>0?yesterdayBeforeInfo.get(0).getPrice():0));
                        goodsQuotation.setUpPercent(upPercent.doubleValue());
                        goodsQuotation.setPrice(tradeRecordList.get(0).getPrice());
                    }
                    goodsQuotation.setTotalPrice(tradeRecordList.stream().mapToDouble(TradeRecord::getTotalPrice).sum());
                }else {
                    goodsQuotation.setHighest(subGoods.getPrice());
                    goodsQuotation.setMinimum(subGoods.getPrice());
                    goodsQuotation.setPrice(subGoods.getPrice());
                    goodsQuotation.setTodayPrice(subGoods.getPrice());
                    goodsQuotation.setTotalNum(0);
                    goodsQuotation.setTotalPrice(0.0);
                    goodsQuotation.setUpPercent(0.0);
                    goodsQuotation.setUpPrice(0.0);
                    goodsQuotation.setYesterdayPrice(0.0);
                }
        }
        aj.put("goodsQuotation",goodsQuotation);
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "实时行情",notes = "实时行情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "区间标识（0：5分 1：时 2：日）",name = "flag",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getRealTimeQuotation")
    @ResponseBody
    public AjaxJson getRealTimeQuotation(String goodsId,String flag){
        AjaxJson aj = new AjaxJson();
        SubGoods subGoods = subGoodsService.get(goodsId);
        List<String> dateList = new ArrayList<>();
        List<Double> minValueList = new ArrayList<>();
        List<Double> maxValueList = new ArrayList<>();
        List<TradeLineInfo> l = new ArrayList<>();
        List<TradingLine> list = new ArrayList<>();
        List<List<Double>> valueList = new ArrayList<>();
        if (subGoods != null){
            TradeRecord tradeRecord = new TradeRecord();
            tradeRecord.setSubGoods(subGoods);
            List<TradeRecord> trades = tradeRecordService.findTradesByDays(tradeRecord);
            if (trades.size()>0){
                for (TradeRecord trade : trades) {
                    List<TradeRecord> tradeRecords = tradeRecordService.getDaysLeastAndEarly(trade);
                    TradeLineInfo tradeLineInfo = new TradeLineInfo();
                    TradingLine tradingLine = new TradingLine();
                    tradingLine.setSubGoods(subGoods);
                    tradingLine.setMinPrice(trade.getMinPrice());
                    tradingLine.setMaxPrice(trade.getMaxPrice());
                    tradingLine.setStartPrice(tradeRecords.get(tradeRecords.size()-1).getPrice());
                    tradingLine.setEndPrice(tradeRecords.get(0).getPrice());
                    tradingLine.setCreateDate(trade.getCreateDate());
                    list.add(tradingLine);
                }
            }
            if (list.size()>0){
                list = list.stream().sorted(Comparator.comparing(TradingLine::getCreateDate)).collect(Collectors.toList());
                for (int i = 0; i < list.size(); i++) {
                    if (list.size()-i<=7){
                        dateList.add(DateUtils.formatDate(list.get(i).getCreateDate(),"MM-dd"));
                    }

                    List<Double> vList = new ArrayList<>();
                    vList.add(list.get(i).getStartPrice());
                    vList.add(list.get(i).getEndPrice());
                    vList.add(list.get(i).getMinPrice());
                    vList.add(list.get(i).getMaxPrice());
                    if (list.size()-i<=7){
                        valueList.add(vList);
                    }
                }
            }

            aj.put("list",valueList);
            aj.put("dateList",dateList);
            aj.put("max",subGoods.getPrice()*3);
            aj.put("goodsName",subGoods.getGoodsName());
        }
//        switch (flag){
//            case "0":
//                TradeRecord tradeRecord = new TradeRecord();
//                tradeRecord.setSubGoods(subGoods);
//                List<TradeRecord> list = tradeRecordService.findFiveMinutesList(tradeRecord);
//                if (list.size()>0){
//                    list = list.stream().sorted(Comparator.comparing(TradeRecord::getCreateDate)).collect(Collectors.toList());
//                        for (int i = 0; i < list.size(); i++) {
//                            dateList.add(DateUtils.formatDate(list.get(i).getCreateDate(),"HH:mm"));
//                            minValueList.add(list.get(i).getMinPrice());
//                            maxValueList.add(list.get(i).getMaxPrice());
//                            if (i == 6){
//                                break;
//                            }
//                        }
//
//                    TradeLineInfo t = new TradeLineInfo();
//                    t.setName("最高价");
//                    t.setData(maxValueList);
//                    TradeLineInfo t1 = new TradeLineInfo();
//                    t1.setName("最低价");
//                    t1.setData(minValueList);
//                    l.add(t);
//                    l.add(t1);
//                }
//                aj.setSuccess(true);
//                aj.put("list",l);
//                aj.put("dateList",dateList);
//                aj.put("max",subGoods.getPrice()*3);
//                aj.put("goodsName",subGoods.getGoodsName());
//                return aj;
//            case "1":
//                SubGoods subGoods1 = new SubGoods();
//                subGoods1.setId(goodsId);
//                TradeRecord tradeRecord1 = new TradeRecord();
//                tradeRecord1.setSubGoods(subGoods1);
//                List<TradeRecord> list1 = tradeRecordService.findFiveDaysList(tradeRecord1);
//                if (list1.size()>0){
////                    for (TradeRecord record : list1) {
////                        record.setTotalPrice(record.getPrice()*record.getNum());
////                    }
//                }
//                aj.setSuccess(true);
//                aj.put("list",list1);
//                return aj;
//            case "2":
//                SubGoods subGoods2 = new SubGoods();
//                subGoods2.setId(goodsId);
//                TradeRecord tradeRecord2 = new TradeRecord();
//                tradeRecord2.setSubGoods(subGoods2);
//                List<TradeRecord> list2 = tradeRecordService.findWeeksList(tradeRecord2);
//                if (list2.size()>0){
////                    for (TradeRecord record : list2) {
////                        record.setTotalPrice(record.getPrice()*record.getNum());
////                    }
//                }
//                aj.setSuccess(true);
//                aj.put("list",list2);
//                return aj;
//            case "3":
//                SubGoods subGoods3 = new SubGoods();
//                subGoods3.setId(goodsId);
//                TradeRecord tradeRecord3 = new TradeRecord();
//                tradeRecord3.setSubGoods(subGoods3);
//                List<TradeRecord> list3 = tradeRecordService.findMonthsList(tradeRecord3);
//                if (list3.size()>0){
////                    for (TradeRecord record : list3) {
////                        record.setTotalPrice(record.getPrice()*record.getNum());
////                    }
//                }
//                aj.setSuccess(true);
//                aj.put("list",list3);
//                return aj;
//            default:
//                SubGoods subGoods4 = new SubGoods();
//                subGoods4.setId(goodsId);
//                TradeRecord tradeRecord4 = new TradeRecord();
//                tradeRecord4.setSubGoods(subGoods4);
//                List<TradeRecord> list4 = tradeRecordService.findList(tradeRecord4);
//                if (list4.size()>0){
////                    for (TradeRecord record : list4) {
////                        record.setTotalPrice(record.getPrice()*record.getNum());
////                    }
//                }
//                aj.setSuccess(true);
//                aj.put("list",list4);
//                return aj;
//        }

       return aj;
    }



    @ApiOperation(value = "认购订单",notes = "认购订单")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getMySubscription")
    @ResponseBody
    public AjaxJson getMySubscription(String memberId){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            SubRecord subRecord = new SubRecord();
            subRecord.setMember(member);
            List<SubRecord> list = subRecordService.findLimitList(subRecord);
            aj.put("list",list);
            aj.setSuccess(true);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }


    @ApiOperation(value = "搜索商品",notes = "搜索商品")
    @ApiImplicitParams({
//			@ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "商品名称",name = "goodsName",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/findGoodsByName")
    @ResponseBody
    public AjaxJson findGoodsByName(String goodsName){
        AjaxJson aj = new AjaxJson();
        SubGoods subGoods = new SubGoods();
        subGoods.setGoodsName(goodsName);
        subGoods.setIsUnloading("0");
        List<SubGoods> list = subGoodsService.findList(subGoods);
        if (list.size()>0){
            for (SubGoods store : list) {
                if (StringUtils.isNotBlank(store.getGoodsPic())){
                    String[] pics = store.getGoodsPic().split("\\|");
                    store.setGoodsPic(pics[0]);
                }
            }
        }
        aj.setSuccess(true);
        aj.put("list",list);
        return aj;
    }


    @ApiOperation(value = "获取提货订单",notes = "获取提货订单")
    @ApiImplicitParams({
			@ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "标识（0待发货1已完成2已取消）",name = "flag",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getTakeGoodsOrders")
    @ResponseBody
    public AjaxJson getTakeGoodsOrders(String memberId,String flag){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            switch (flag){
                case "0":
                    TakeOrder takeOrder = new TakeOrder();
                    takeOrder.setMember(member);
                    takeOrder.setOrderStatus("0");
                    List<TakeOrder> list = takeOrderService.findLimitList(takeOrder);
                    if (list.size()>0){
                        for (TakeOrder order : list) {
                            TakeGoods takeGoods = takeGoodsService.get(order.getTakeGoods().getId());
                            if (StringUtils.isNotBlank(takeGoods.getGoodsPic())){
//                                order.setPic(takeGoods.getGoodsPic().split("//|")[0]);
                                order.setPic(takeGoods.getGoodsPic());
                            }
                        }
                    }
                    aj.put("list",list);
                    aj.setSuccess(true);
                    return aj;
                case "1":
                    TakeOrder takeOrder1 = new TakeOrder();
                    takeOrder1.setMember(member);
                    takeOrder1.setOrderStatus("1");
                    List<TakeOrder> list1 = takeOrderService.findLimitList(takeOrder1);
                    if (list1.size()>0){
                        for (TakeOrder order : list1) {
                            TakeGoods takeGoods = takeGoodsService.get(order.getTakeGoods().getId());
                            if (StringUtils.isNotBlank(takeGoods.getGoodsPic())){
//                                order.setPic(takeGoods.getGoodsPic().split("//|")[0]);
                                order.setPic(takeGoods.getGoodsPic());
                            }
                        }
                    }
                    aj.put("list",list1);
                    aj.setSuccess(true);
                    return aj;
                case "2":
                    TakeOrder takeOrder2 = new TakeOrder();
                    takeOrder2.setMember(member);
                    takeOrder2.setOrderStatus("2");
                    List<TakeOrder> list2 = takeOrderService.findLimitList(takeOrder2);
                    if (list2.size()>0){
                        for (TakeOrder order : list2) {
                            TakeGoods takeGoods = takeGoodsService.get(order.getTakeGoods().getId());
                            if (StringUtils.isNotBlank(takeGoods.getGoodsPic())){
//                                order.setPic(takeGoods.getGoodsPic().split("//|")[0]);
                                order.setPic(takeGoods.getGoodsPic());
                            }
                        }
                    }
                    aj.put("list",list2);
                    aj.setSuccess(true);
                    return aj;
                default:
                    return aj;
            }


        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }

    @ApiOperation(value = "获取提货订单详情",notes = "获取提货订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "订单号",name = "orderNo",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getTakeGoodsOrdersDetail")
    @ResponseBody
    public AjaxJson getTakeGoodsOrdersDetail(String memberId,String orderNo){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            TakeOrder takeOrder = new TakeOrder();
            takeOrder.setOrderNo(orderNo);
            takeOrder.setMember(member);
            List<TakeOrder> list = takeOrderService.findList(takeOrder);
            if (list.size()>0){
                for (TakeOrder order : list) {
                    TakeGoods takeGoods = takeGoodsService.get(order.getTakeGoods().getId());
                    if (StringUtils.isNotBlank(takeGoods.getGoodsPic())){
//                        order.setPic(takeGoods.getGoodsPic().split("//|")[0]);
                        order.setPic(takeGoods.getGoodsPic());
                    }
                }
            }
            if (list.size()>0){
                aj.put("detail",list.get(0));
                aj.setSuccess(true);
            }else {
                aj.setSuccess(false);
                aj.setMsg("订单信息有误");
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }



    @ApiOperation(value = "获取用户指定商品最大可卖出数量",notes = "获取用户指定商品最大可卖出数量")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getSaleAmountByGoods")
    @ResponseBody
    public AjaxJson getSaleAmountByGoods(String memberId,String goodsId){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            SubGoods subGoods = subGoodsService.get(goodsId);
            if (subGoods != null){
                PositionAssets positionAssets = new PositionAssets();
                positionAssets.setMember(member);
                positionAssets.setSubGoods(subGoods);
                positionAssets.setIsApply("0");
                List<PositionAssets> list = positionAssetsService.findList(positionAssets);
                //查询已挂待交易的买入订单
                SaleOrder s = new SaleOrder();
                s.setMember(member);
                s.setIsRevoke("0");
                s.setIsDeal("0");
                s.setSubGoods(subGoods);
                List<SaleOrder> slist = saleOrderService.findList(s);
                int saleNum = 0;
                if (slist.size()>0){
                    saleNum = list.get(0).getGoodsNum()-slist.stream().mapToInt(SaleOrder::getNonNum).sum();
                }else {
                    if (list.size()>0){
                        saleNum=list.get(0).getGoodsNum();
                    }
                }
                aj.put("amount",saleNum);
            }else {
                aj.setSuccess(false);
                aj.setMsg("商品信息有误");
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }


    @ApiOperation(value = "获取指定商品交易价格区间",notes = "获取指定商品交易价格区间")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "商品id",name = "goodsId",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getSalePriceByGoods")
    @ResponseBody
    public AjaxJson getSalePriceByGoods(String memberId,String goodsId){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            SubGoods subGoods = subGoodsService.get(goodsId);
            if (subGoods != null){
                List<TradeRecord> tlist = tradeRecordService.findYesterdayBeforeInfo(subGoods.getId());
                if (tlist.size()>0){
                    double upMoney = BigDecimal.valueOf(tlist.get(0).getPrice()*1.1).setScale(2,BigDecimal.ROUND_HALF_DOWN).doubleValue();
                    double downMoney = BigDecimal.valueOf(tlist.get(0).getPrice()-(tlist.get(0).getPrice()*0.1)).setScale(2,BigDecimal.ROUND_HALF_DOWN).doubleValue();
                    aj.put("upMoney",upMoney);
                    aj.put("downMoney",downMoney);
                    return aj;
                }else {
                    double upMoney = BigDecimal.valueOf(subGoods.getPrice()*1.1).setScale(2,BigDecimal.ROUND_HALF_DOWN).doubleValue();
                    double downMoney = BigDecimal.valueOf(subGoods.getPrice()-(subGoods.getPrice()*0.1)).setScale(2,BigDecimal.ROUND_HALF_DOWN).doubleValue();
                    aj.put("upMoney",upMoney);
                    aj.put("downMoney",downMoney);
                    return aj;
                }
            }else {
                aj.setSuccess(false);
                aj.setMsg("商品信息有误");
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }



    @ApiOperation(value = "资产发货订单",notes = "资产发货订单")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "订单状态(0可发货1待发货2已完成)",name = "flag",required = true,dataType = "String",paramType = "query"),
    })
    @GetMapping("/getPositionOrders")
    @ResponseBody
    public AjaxJson getPositionOrders(String memberId,String flag){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            if ("0".equals(flag)){
                //可申请订单
                List<PositionOrder> list = new ArrayList<>();
                //持仓可申请发货的
                PositionAssets positionAssets = new PositionAssets();
                positionAssets.setMember(member);
                List<PositionAssets> nonList = positionAssetsService.findNonList(positionAssets);
                if (nonList.size() > 0){
                    for (PositionAssets assets : nonList) {
                        PositionOrder positionOrder = new PositionOrder();
                        positionOrder.setOrderType("0");
                        positionOrder.setPositionId(assets.getId());
                        positionOrder.setGoodsName(assets.getGoodsName());
                        positionOrder.setMember(member);
                        positionOrder.setNum(assets.getGoodsNum());
                        positionOrder.setPrice(assets.getNowPrice());
                        positionOrder.setTotalPrice(assets.getNowTotal());
                        positionOrder.setUpdateDate(assets.getUpdateDate());
                        SubGoods subGoods = subGoodsService.get(assets.getSubGoods().getId());
                        if (subGoods != null){
                            positionOrder.setPic(subGoods.getGoodsPic());
                        }
                        list.add(positionOrder);
                    }
                }
                //锁仓可申请发货的
                FreezingAssets freezingAssets = new FreezingAssets();
                freezingAssets.setMember(member);
                List<FreezingAssets> freezingNonList = freezingAssetsService.findNonList(freezingAssets);
                if (freezingNonList.size() > 0){
                    for (FreezingAssets assets : freezingNonList) {
                        PositionOrder positionOrder = new PositionOrder();
                        positionOrder.setOrderType("1");
                        positionOrder.setPositionId(assets.getId());
                        positionOrder.setGoodsName(assets.getGoodsName());
                        positionOrder.setMember(member);
                        positionOrder.setNum(assets.getNum());
                        positionOrder.setPrice(assets.getNowPrice());
                        positionOrder.setTotalPrice(assets.getNowTotal());
                        positionOrder.setUpdateDate(assets.getUpdateDate());
                        SubGoods subGoods = subGoodsService.get(assets.getSubGoods().getId());
                        if (subGoods != null){
                            positionOrder.setPic(subGoods.getGoodsPic());
                        }
                        list.add(positionOrder);
                    }
                }
                list = list.stream().sorted(Comparator.comparing(PositionOrder::getUpdateDate).reversed()).collect(Collectors.toList());
                aj.setSuccess(true);
                aj.put("list",list);
            }else if ("1".equals(flag)){
                //待发货订单
                PositionOrder positionOrder = new PositionOrder();
                positionOrder.setMember(member);
                positionOrder.setOrderStatus("0");
                List<PositionOrder> list = positionOrderService.findList(positionOrder);
                aj.setSuccess(true);
                aj.put("list",list);
            }else {
                //已完成订单
                PositionOrder positionOrder = new PositionOrder();
                positionOrder.setMember(member);
                positionOrder.setOrderStatus("1");
                List<PositionOrder> list = positionOrderService.findList(positionOrder);
                aj.setSuccess(true);
                aj.put("list",list);
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }



    @ApiOperation(value = "申请发货",notes = "申请发货")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "订单类型(0持仓订单1锁仓订单)",name = "flag",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "资产id",name = "positionId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "提货数量",name = "applyNum",required = true,dataType = "Integer",paramType = "query"),
    })
    @PostMapping("/applyExpressPosition")
    @ResponseBody
    public AjaxJson applyExpressPosition(String memberId,String flag,String positionId,Integer applyNum){
        AjaxJson aj = new AjaxJson();
        try {
            Member member = memberService.get(memberId);
            if (member != null){
                if (applyNum <= 0){
                    aj.setSuccess(false);
                    aj.setMsg("提货数量有误");
                    return aj;
                }
                if ("1".equals(flag)){
                    //如果是锁仓资产申请提货，需要查询是否持仓已经提完，否则不允许
                    PositionAssets positionAssets = new PositionAssets();
                    positionAssets.setMember(member);
                    List<PositionAssets> nonList = positionAssetsService.findNonList(positionAssets);
                    if (nonList.size() > 0){
                        aj.setSuccess(false);
                        aj.setMsg("请优先提货持仓资产");
                        return aj;
                    }
                }
                positionOrderService.applyExpress(member,flag,positionId,applyNum);
                aj.setSuccess(true);
                aj.setMsg("申请成功");
            }else {
                aj.setSuccess(false);
                aj.setMsg("用户信息有误");
            }
        }catch (Exception e){
            e.printStackTrace();
            aj.setSuccess(false);
            aj.setMsg(e.getMessage());
        }
        return aj;
    }


    @ApiOperation(value = "取消申请发货",notes = "取消申请发货")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",name = "memberId",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "订单id",name = "orderId",required = true,dataType = "String",paramType = "query"),
    })
    @PostMapping("/cancelExpressPosition")
    @ResponseBody
    public AjaxJson cancelExpressPosition(String memberId,String orderId){
        AjaxJson aj = new AjaxJson();
        try {
            Member member = memberService.get(memberId);
            if (member != null){
                PositionOrder positionOrder = positionOrderService.get(orderId);
                if (positionOrder == null){
                    aj.setSuccess(false);
                    aj.setMsg("订单信息有误");
                    return aj;
                }
                if (!"0".equals(positionOrder.getOrderStatus())){
                    aj.setSuccess(false);
                    aj.setMsg("该订单并非待发货，不可取消");
                    return aj;
                }
                positionOrderService.cancel(positionOrder);
                aj.setSuccess(true);
                aj.setMsg("取消成功");
            }else {
                aj.setSuccess(false);
                aj.setMsg("用户信息有误");
            }
        }catch (Exception e){
            e.printStackTrace();
            aj.setSuccess(false);
            aj.setMsg(e.getMessage());
        }
        return aj;
    }


}
